/******************************************************************************
 * Copyright 2022 The Airos Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

#pragma once
#include <pthread.h>
#include <stdint.h>

#include <list>
#include <memory>
#include <string>
#include <unordered_map>

#include "framework/common.h"
#include "framework/list.h"

namespace air {
namespace link {

class Context;
class ContextManager final {
 public:
  ContextManager();
  virtual ~ContextManager();

  /* 注册actor */
  bool RegContext(const std::shared_ptr<Context>& ctx);

  /* 获得actor名对应的actor */
  std::shared_ptr<Context> GetContext(const std::string& actor_name);

  /* 获得一个待处理的actor */
  std::shared_ptr<Context> GetContextWithMsg();

  /* 将有消息的actor放入链表 */
  void PushContext(std::shared_ptr<Context> ctx);

 private:
  void PrintWaitQueue();

  /// 当前注册actor数量
  uint32_t ctx_count_;
  /// 待处理actor链表
  std::list<std::weak_ptr<Context>> wait_queue_;
  /// 读写锁
  pthread_rwlock_t rw_;
  /// key: context name
  /// value: context
  std::unordered_map<std::string, std::shared_ptr<Context>> ctxs_;
};

}  // namespace link
}  // namespace air
